package com.atguigu.gmall.order.controller;


import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import sun.security.krb5.internal.PAData;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/order")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 确认订单
     * @param request
     * @return
     */
    @GetMapping("auth/trade")
    public Result<Map<String, Object>> trade(HttpServletRequest request){
        //userAddressList  detailArrayList  totalNum totalAmount

        String userId = AuthContextHolder.getUserId(request);
        //获取用户地址集合
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);
        //获取选中购物项集合
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);

        List<OrderDetail> orderDetailArrayList = new ArrayList<>();
        int totalNum = 0;
        for (CartInfo cartInfo : cartCheckedList) {
            OrderDetail orderDetail = new OrderDetail();

            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setSkuNum(cartInfo.getSkuNum());

            orderDetailArrayList.add(orderDetail);

            totalNum +=orderDetail.getSkuNum();
        }

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(orderDetailArrayList);
        orderInfo.sumTotalAmount();

        Map<String, Object> map = new HashMap<>();
        map.put("userAddressList",userAddressList);
        map.put("detailArrayList",orderDetailArrayList);
        map.put("totalNum",totalNum);
        map.put("totalAmount",orderInfo.getTotalAmount());
        //获取一个tradeNo
        String tradeNo = orderService.getTradeNo(userId);
        map.put("tradeNo",tradeNo);

        return Result.ok(map);
    }

    /**
     * 提交订单
     * @param orderInfo
     * @param request
     * @return
     */
    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));

        String tradeNo = request.getParameter("tradeNo");
        //校验流水号，防止重复提交
        boolean flag = orderService.checkTradeNo(tradeNo, userId);
        if(!flag){
            return Result.fail().message("不能重复提交订单");
        }
        orderService.deleteTradeNo(userId);

        List<String> errorList = new ArrayList<>();
        List<CompletableFuture> futureList = new ArrayList<>();

        //校验库存系统
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if(!CollectionUtils.isEmpty(orderDetailList)){
            for (OrderDetail orderDetail : orderDetailList) {
                CompletableFuture<Void> stockCompletableFuture = CompletableFuture.runAsync(() -> {
                    boolean res = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                    if (!res) {
                        errorList.add(orderDetail.getSkuName()+"\t 库存不足！");
                    }
                },threadPoolExecutor);

                futureList.add(stockCompletableFuture);

                CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {

                    BigDecimal orderPrice = orderDetail.getOrderPrice();
                    BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());



                    String msg = "";
                    if (orderPrice.compareTo(skuPrice) != 0) {

                        String cartKey = RedisConst.USER_KEY_PREFIX+userId+RedisConst.USER_CART_KEY_SUFFIX;
                        CartInfo cartInfo = (CartInfo) redisTemplate.opsForHash().get(cartKey, orderDetail.getSkuId().toString());
                        cartInfo.setSkuPrice(skuPrice);
                        redisTemplate.opsForHash().put(cartKey,orderDetail.getSkuId().toString(),cartInfo);

                        if (orderPrice.compareTo(skuPrice) > 0) {
                            msg = "降价" + orderPrice.subtract(skuPrice).abs();
                        } else {
                            msg = "涨价" + orderPrice.subtract(skuPrice).abs();
                        }
                        errorList.add(orderDetail.getSkuName() + msg);
                    }

                },threadPoolExecutor);
                futureList.add(priceCompletableFuture);
            }
        }
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()])).join();

        //  判断多线程中是否有异常！
        if (errorList.size()>0){
            //  说明有异常操作！ 将集合中的数据链接成一个字符串显示出来! {"仙女渐变色库存不足!","深蓝星球价格有变动"}
            return Result.fail().message(StringUtils.join(errorList,","));
        }

        Long orderId = orderService.saveOrderInfo(orderInfo);

        return Result.ok(orderId);


    }

    //我的订单
    @GetMapping("auth/{page}/{limit}")
    public Result<IPage<OrderInfo>> index(@PathVariable Long page,
                                          @PathVariable Long limit,
                                          HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        Page<OrderInfo> orderInfoPage = new Page<OrderInfo>(page, limit);
        IPage iPage = orderService.getOrderList(orderInfoPage,userId);
        return Result.ok(iPage);
    }

    /**
     * 内部调用获取订单
     * @param orderId
     * @return
     */
    @GetMapping("inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable(value = "orderId") Long orderId){
        return orderService.getOrderInfo(orderId);
    }

    //http://localhost:8204/api/order/orderSplit拆单url
    /**
     * 拆单业务
     * @param request
     * @return
     */
    @PostMapping("orderSplit")
    public String orderSplit(HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        String wareSkuMap = request.getParameter("wareSkuMap");
        List<OrderInfo> orderInfoList = orderService.orderSplit(Long.parseLong(orderId), wareSkuMap);
        /*ArrayList<Map> maps = new ArrayList<>();

//        for (OrderInfo orderInfo : orderInfoList) {
//            Map map = orderService.initWare(orderInfo.getId());
////            maps.add(map);
//        }*/
        List<Map> mapList = orderInfoList.stream().map(orderInfo -> {
            Map map = orderService.initWare(orderInfo);
            return map;
        }).collect(Collectors.toList());

        return JSON.toJSONString(mapList);
    }



}
